﻿using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Sripirom.ATS.Core.ExceptionHandler;
using Sripirom.ATS.Core.Messaging;

namespace Sripirom.ATS.Core.ExceptionHandler
{
    public class MessageExceptionHandler : IErrorHandler
    {                
        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            fault = Message.CreateMessage(version, FaultCode.CreateReceiverFaultCode(Errors.UNHANDLED_EXCEPTION, "http://www.sripirom.com"), "Unhandled exception", "");
            
            Int32 headerPosition = OperationContext.Current.IncomingMessageHeaders.FindHeader("Headers", "http://schemas.microsoft.com/42");
            if (headerPosition == 0)
            {
                XmlObjectSerializer serializer = new DataContractSerializer(typeof(ServiceMessageHeader), "Headers", "http://schemas.microsoft.com/42", null, Int32.MaxValue, false, false, null);
                var header = OperationContext.Current.IncomingMessageHeaders.GetHeader<ServiceMessageHeader>(headerPosition, serializer);

                fault.Headers.Add(new ServiceHeader(header));
            }
              
        }
    }
}
